using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;

namespace App1
{
    /// <summary>
    /// 音频播放器窗口
    /// </summary>
    public sealed partial class AudioPlayerWindow : Window
    {
        private FileItem _fileItem;
        private bool _isDraggingSlider = false;

        public AudioPlayerWindow(FileItem fileItem)
        {
            this.InitializeComponent();
            _fileItem = fileItem;
            InitializePlayer();
        }

        private void InitializePlayer()
        {
            // 设置窗口标题为文件名
            FileNameTextBlock.Text = _fileItem.Name;

            // 加载音频文件
            try
            {
                // 这里假设文件路径是有效的
                // 实际应用中需要处理网络路径或共享路径
                AudioPlayer.Source = new Uri(_fileItem.Path);
                AudioPlayer.Play();

                // 更新进度条和时间显示
                AudioPlayer.CurrentStateChanged += AudioPlayer_CurrentStateChanged;
                AudioPlayer.MediaOpened += AudioPlayer_MediaOpened;
                AudioPlayer.MediaEnded += AudioPlayer_MediaEnded;

                // 定时更新进度
                var timer = new DispatcherTimer();
                timer.Interval = TimeSpan.FromMilliseconds(500);
                timer.Tick += Timer_Tick;
                timer.Start();
            }
            catch (Exception ex)
            {
                // 显示错误信息
                var errorDialog = new ContentDialog
                {
                    Title = "播放错误",
                    Content = $"无法播放音频: {ex.Message}",
                    CloseButtonText = "确定"
                };
                errorDialog.ShowAsync();
            }
        }

        private void AudioPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            // 媒体文件打开后更新总时长
            UpdateTimeDisplay();
            ProgressSlider.Maximum = AudioPlayer.NaturalDuration.TimeSpan.TotalSeconds;
        }

        private void AudioPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            // 更新播放状态
            if (AudioPlayer.CurrentState == MediaElementState.Playing)
            {
                // 播放状态
                PlayPauseButton.Content = "暂停";
            }
            else if (AudioPlayer.CurrentState == MediaElementState.Paused ||
                     AudioPlayer.CurrentState == MediaElementState.Stopped)
            {
                // 暂停或停止状态
                PlayPauseButton.Content = "播放";
            }
        }

        private void AudioPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            // 音频播放结束，重新播放
            AudioPlayer.Position = TimeSpan.Zero;
            AudioPlayer.Play();
        }

        private void Timer_Tick(object sender, object e)
        {
            // 定时更新进度条
            if (!_isDraggingSlider)
            {
                ProgressSlider.Value = AudioPlayer.Position.TotalSeconds;
                UpdateTimeDisplay();
            }
        }

        private void UpdateTimeDisplay()
        {
            // 更新时间显示
            var currentTime = AudioPlayer.Position;
            var totalTime = AudioPlayer.NaturalDuration.HasTimeSpan ?
                AudioPlayer.NaturalDuration.TimeSpan : TimeSpan.Zero;

            TimeTextBlock.Text = $"{FormatTime(currentTime)} / {FormatTime(totalTime)}";
        }

        private string FormatTime(TimeSpan time)
        {
            // 格式化时间为 时:分:秒 或 分:秒
            if (time.Hours > 0)
                return $"{time.Hours:D2}:{time.Minutes:D2}:{time.Seconds:D2}";
            else
                return $"{time.Minutes:D2}:{time.Seconds:D2}";
        }

        // 窗口控制按钮事件
        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        // 播放/暂停按钮事件
        private void PlayPauseButton_Click(object sender, RoutedEventArgs e)
        {
            if (AudioPlayer.CurrentState == MediaElementState.Playing)
            {
                AudioPlayer.Pause();
            }
            else
            {
                AudioPlayer.Play();
            }
        }

        // 进度条值改变事件
        private void ProgressSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
        {
            if (!_isDraggingSlider)
            {
                AudioPlayer.Position = TimeSpan.FromSeconds(e.NewValue);
            }
        }

        // 进度条拖动开始事件
        private void ProgressSlider_DragStarted(object sender, DragStartedEventArgs e)
        {
            _isDraggingSlider = true;
        }

        // 进度条拖动完成事件
        private void ProgressSlider_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            _isDraggingSlider = false;
            AudioPlayer.Position = TimeSpan.FromSeconds(ProgressSlider.Value);
        }

        // 倍速选择事件
        private void PlaybackRateComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PlaybackRateComboBox.SelectedItem is ComboBoxItem item)
            {
                var rateText = item.Content.ToString();
                if (rateText.EndsWith("x"))
                {
                    double rate;
                    if (double.TryParse(rateText.Replace("x", ""), out rate))
                    {
                        AudioPlayer.PlaybackRate = rate;
                    }
                }
            }
        }
    }
}